<?php
namespace app\front\logic;
use think\facade\Db;
use app\front\logic\OrderThirdPayLogLogic;


class RechargeOrderLogic{
	public static $init;
	static function init(){
		if (!isset(self::$init)) {//判断是否以前创建了当前类的实例
            $c = __CLASS__;//获取类名
            self::$init = new static;//如果没有创建，实例化当前类，这里实现类只实例化一次
        }
        return self::$init;//返回类的实例
	}

	//新增订单
	function add($data=[]){
		if(!$data){
			return 139;
		}
		Db::startTrans();
		try {
			//新增数据库喽
			$id = Db::name('order_recharge')->insertGetId($data);
			$ldata = [];
			$ldata['out_order_id'] = $id;
			$ldata['order_type'] = 10;
			$ldata['payment_type'] = $data['pay_type'];
			$ldata['member_id'] = $data['member_id'];
			// $ldata['trade_number'] = $data['recharge_sn']."_".rand(100,999);
			$ldata['pay_amount'] = $data['recharge_amount'];
			$ldata['payment_status'] = 10;
			$ldata['begin_time'] = date('Y-m-d H:i:s');
			$lid = OrderThirdPayLogLogic::init()->add($ldata);
			if(!$id || !$lid){
				Db::rollback();
				return 139;
			}
			Db::commit();
		    return 0;
		} catch (\Exception $e) {
			// print_r($e->getMessage());
		    // 回滚事务
		    Db::rollback();
		    return 139;
		}
	}

	//获取订单列表
	function getOrderList($member_id=0, $exchange_rate=1){
		$page_size = input('page_size', 10);
		$start_time = input('start_time','');
		$end_time = input('end_time','');
		$start_time && $start_time = $start_time." 00:00:00";
		$end_time && $end_time = $end_time." 23:59:59";
		$fields = "id, member_id, recharge_sn, 
				    round(recharge_amount / $exchange_rate, 2) as recharge_amount,
				    number,
				    round(level_amount / $exchange_rate, 2) as level_amount,
				    round(gift_amount / $exchange_rate, 2) as gift_amount,
				    round(first_amount / $exchange_rate, 2) as first_amount,
				    round(origin_invitation_amount / $exchange_rate, 2) as origin_invitation_amount,
				    pay_type, status, create_time, pay_time";

		$obj = Db::name('order_recharge')
				->field($fields)
				->where('status', 20)
				->where('member_id', $member_id);
		if($start_time){
			$obj->where('create_time','>=', $start_time);
		}

		if($end_time){
			$obj->where('create_time','<=', $end_time);
		}
		$lists = $obj->order('id desc')
					->paginate($page_size);
		return $lists;
	}

	

}